#!/usr/bin/env python3.6.1
# -*- coding: utf-8 -*-
__author__ = 'James Wu'

from imp import reload
import os
import sys
reload(sys)
import json
import urllib.parse
import urllib.request
import plistlib
import subprocess
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
from optparse import OptionParser
import smtplib

#可以使Release  也可以是Debug
CONFIGURATION = "Release"
EXPORT_BUILD_PLIST = "build.plist"
EXPORT_MAIN_DIRECTORY = "~/Desktop/"

FIR_API_TOKEN = "450207a077d474025962aac6b87e3ecb"

MAIL_FROM_ADDRESS = "hzdustin@sina.com"
MAIL_PASSWORD = "huang120504"
SMTP_SERVER = "smtp.sina.com"

MAIL_TO_ADDRESS = '497758633@qq.com'
# MAIL_TO_ADDRESS = '497758633@qq.com,2746665602@qq.com'

def usage():
  print('********************************Auto*******************************')
  print('@author 黄振, 17-04-13 16:30')
  print('Auto Packaging & Publish Tool')
  print('********************************Auto*******************************')

#************************************clean工程***********************************
def cleanBuildFile(buildFile):
	cleanCmd = "rm -r %s" %(buildFile)
	process = subprocess.Popen(cleanCmd, shell = True)
	process.wait()
	cleanReturnCode = process.returncode
	if cleanReturnCode == 0:
		print('************************CleanBuild文件成功************************')	
	else:
		print('************************CleanBuild文件失败************************')	
	# os.system(cleanCmd)

def cleanArchiveFile(archiveFile):
	cleanCmd = "rm -r %s" %(archiveFile)
	process = subprocess.Popen(cleanCmd, shell = True)
	process.wait()
	cleanReturnCode = process.returncode
	if cleanReturnCode == 0:
		print('************************Clean成功************************')	
	else:
		print('************************Clean失败************************')	
	# os.system(cleanCmd)
#************************************achive工程***********************************
def buildWorkspace(workspace, scheme):
	buildingPath = buildPath(scheme)
	archivePath = buildArchivePath(scheme)
	cleanCmd = 'xcodebuild -target %s -configuration %s -sdk iphoneos clean SYMROOT=%s' %(scheme, CONFIGURATION, buildingPath)
	os.system(cleanCmd)
	archiveCmd = 'xcodebuild archive  -workspace %s -scheme %s -archivePath %s' %(workspace, scheme, archivePath)
	archiveReturnCode = os.system(archiveCmd)
	if archiveReturnCode == 0:
		print('************************Archive成功************************')
		exportArchive(archivePath, scheme)
		cleanArchiveFile(archivePath)
		cleanBuildFile(buildingPath)

	else:
		print('************************Archive失败************************')
		updateBuildNumber(scheme,False)
		cleanArchiveFile(archivePath)
		cleanBuildFile(buildingPath)
	# os.system(archiveCmd) 在终端输入
def exportArchive(archivePath, scheme):
	exportDirectory = buildExportPath(scheme)
	exportCmd = "xcodebuild -exportArchive -archivePath %s -exportPath %s -exportOptionsPlist %s" %(archivePath, exportDirectory, EXPORT_BUILD_PLIST)
	process = subprocess.Popen(exportCmd, shell=True)
	process.wait()
	exportReturnCode = process.returncode
	if exportReturnCode == 0:
		print('************************Export成功************************')
		upIpaFir(exportDirectory ,scheme)
	else:
		print('************************Export失败************************')
		updateBuildNumber(scheme,False)
	# os.system(exportCmd)
#上传fir.m
def upIpaFir(exportDirectory, scheme):
	ipacmd = "ls %s" %(exportDirectory)
	process = subprocess.Popen(ipacmd, stdout=subprocess.PIPE, shell=True)
	(stdoutdata, stderrdata) = process.communicate()
	ipaName = stdoutdata.decode('utf8').strip()
	ipaPath = "%s/%s" % (exportDirectory,ipaName)


	uploadResult=os.system('fir publish '+ipaPath+' -T '+FIR_API_TOKEN)
	if uploadResult == 0:
		print('************************上传Fir成功************************')
		send_mail(scheme)
	else:
		print('************************上传Fir失败************************')	
	

def updateBuildNumber(scheme,isSuccess):
	plistPath=os.getcwd()+"/"+scheme+"/Info.plist"
	data=plistlib.readPlist(plistPath)
	oldBuildVersion=data['CFBundleVersion']
	if isSuccess == True:
		data['CFBundleVersion']=str(int(oldBuildVersion)+1)	
	else:
		data['CFBundleVersion']=str(int(oldBuildVersion)-1)
	plistlib.writePlist(data, plistPath)

#格式化地址
def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))

# 发邮件
def send_mail(scheme):
	try:  
		plistPath=os.getcwd()+"/"+scheme+"/Info.plist"
		data=plistlib.readPlist(plistPath)
		appVersion=data['CFBundleShortVersionString']
		appBuildVersion=data['CFBundleVersion']
		MAILLIST = MAIL_TO_ADDRESS.split(',')
		msg = MIMEText('<html><body><h1>新版本【护理管理】已经发布!</h1>' +
					   '<p ><a href="http://fir.im/s61u">点击进行安装</a></p>' + 
					   '</body></html>', 'html', 'utf-8')
		msg['From'] = _format_addr('黄振： <%s>' % MAIL_FROM_ADDRESS)
		msg['To'] = _format_addr('接收人员： <%s>' % MAIL_TO_ADDRESS)
		msg['Subject'] = Header('✈️ ✈️ 【护理管理】新版本可用 Build Version:{buildNumber}'.format(version=appVersion,buildNumber=appBuildVersion), 'utf-8').encode()
		server = smtplib.SMTP(SMTP_SERVER, 25)
		server.set_debuglevel(1)
		server.login(MAIL_FROM_ADDRESS, MAIL_PASSWORD)
		server.sendmail(MAIL_FROM_ADDRESS, MAILLIST, msg.as_string())	
		server.quit()
		print("************************邮件发送成功************************")  
	except smtplib.SMTPException as e:  
		print(e)  
		print("************************Error:无法发送邮件************************")

#************************************a设置工程路径***********************************
def buildExportPath(scheme):
	dateCmd = 'date "+[%m-%d_%H-%M-%S]"'
	process = subprocess.Popen(dateCmd, stdout=subprocess.PIPE, shell=True)
	(stdoutdata, stderrdata) = process.communicate()
	exportDirectory = "%s%s%s" %(EXPORT_MAIN_DIRECTORY, scheme, stdoutdata.decode('utf8').strip())
	return exportDirectory

def buildPath(scheme):
	process = subprocess.Popen("pwd", stdout=subprocess.PIPE)
	(stdoutdata, stderrdata) = process.communicate()
	archiveName = "%s.xcarchive" %(scheme)
	archivePath = stdoutdata.decode('utf8').strip() + '/build'
	return archivePath

def buildArchivePath(scheme):
	process = subprocess.Popen("pwd", stdout=subprocess.PIPE)
	(stdoutdata, stderrdata) = process.communicate()
	archiveName = "%s.xcarchive" %(scheme)
	archivePath = stdoutdata.decode('utf8').strip() + '/build/' + archiveName
	return archivePath

def xcodebuild(options):
	workspace = options.workspace
	scheme = options.scheme
	buildWorkspace(workspace,scheme)

def main():
	usage()
	parser = OptionParser()
	parser.add_option("-w", "--workspace", help="Build the workspace name.xcworkspace.", metavar="name.xcworkspace")
	parser.add_option("-s", "--scheme", help="Build the scheme specified by schemename. Required if building a workspace.", metavar="schemename")
	(options, args) = parser.parse_args()
	updateBuildNumber(options.scheme,True)
	xcodebuild(options)
	
	# send_mail(options.scheme)

if __name__ == '__main__':
	main()

# python3 auto.py -w AutoBuildForNative.workspace -s AutoBuildForNative
